// pages/prod/prod.js
const app = getApp()
var http = require('../../utils/http.js');
var config = require('../../utils/config.js');
var util = require('../../utils/util.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    shopId: 1,
    picDomain: config.picDomain,
    indicatorDots: true,  //指示点
    indicatorColor: '#f2f2f2',  //指示点颜色
    indicatorActiveColor: '#e43130',  //指示点选中时颜色
    isAuthInfo: true,
    autoplay: true,
    interval: 3000,
    duration: 1000,
    prodNum: 1,
    totalCartNum: 0,
    groupActivityId: 0, //团购活动ID
    isGroupProd: false, //是否有效团购商品
    pic: "",
    imgs: '',
    prodName: '',
    price: 0,
    actPrice: 0,
    content: '',
    prodId: 0,
    brief: '',
    skuId: 0,
    popupShow: false,
    // 是否获取过用户领取过的优惠券id
    loadCouponIds: false,
    skuShow: false,
    skuGroupShow: false,
    commentShow: false,
    couponList: [],
    skuList: [],
    skuGroup: {},
    findSku: true,
    defaultSku: undefined,
    detaultGroupSku: undefined,
    selectedProp: [],
    selectedPropObj: {},
    selectedProperties: "",
    propKeys: [],
    allProperties: [],
    prodCommData: {},
    prodCommPage: {
      current: 0,
      pages: 0,
      records: []
    },
    littleCommPage: [],
    evaluate: -1,
    isCollection: false,
    shareShow: false,
    isDist: false, //是否分销员
    isDistProd: false, //是否分销商品
    distributionCardNo: "", //分销员卡号

    wxCodeShow: false, //是否显示二维码弹层
    shareWxCode: "", //分享二维码图片路径
    groupActivity: {}, // 团购活动
    endOfGroupTime: {}, // 距离团购活动结束还剩多久
    joinGroupList: [], // 可加入的团列表
    skuShowType: 0, // sku的显示类型 0普通sku 1拼团sku
    joinGroupListTimeOut: null,
    groupActivityTimeOut: null,
    showBacktop: false, //回到顶部显隐
    prodDiscountList: [], // 商品促销活动列表
    groupActivityTimeOut: null,
    totalStocks: 0, // 活动剩余库存
    hasMaxNum: false, // 是否限购
    maxNum: 0, // 限购数量

    videoContext: '', // 视频组件
    isPlaying: false, // 视频是否播放中
    currentSwiper: 0, // 当前轮播index
    touchS: [0, 0], // 滑动屏幕开始坐标
    touchE: [0, 0], // 滑动屏幕结束坐标
    showDiscountPopup: false, //促销弹窗显隐

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)

    //根据Ticket获取保存的内容(pc团购扫码 || 分销)
    if (options.scene) {
      this.setData({
        scene: options.scene,
      })
      this.getContent() //根据Ticket获取保存的内容
    }
    // 加载商品信息
    if (options.prodid) {
      this.setData({
        prodId: options.prodid,
      });
      this.executionFunction() //所有需要加载的函数
    }
    if(options.cardno && options.type ==2){
      this.bindDistUser(options.cardno)
      this.setData({
        distributionCardNo: options.cardno,
      })
    }

    //分销员转发过来的，需要绑定用户
    // if (options.cardno) {
    //   this.bindDistUser(options.cardno);
    // }

    // if (options.scene) {
    //   const scene = decodeURIComponent(options.scene);
    //   var params = scene.split(",");
    //   this.setData({
    //     prodId: params[0],
    //     distributionCardNo: params[1]
    //   });
    // }

  },

  /**
   * 执行函数
   */
  executionFunction: function() {
    // 加载商品信息
    this.getProdInfo();
    // 加载评论数据
    this.getProdCommData();
    // 加载评论项
    this.getLittleProdComm();
    // 查看用户是否关注
    this.getCollection();
    //查询用户 是否为分销员
    this.getDistInfo();
  },

  /**
   * 根据Ticket获取保存的内容
   */
  getContent: function () {
    http.request({
      url: "/qrcodeTicket/getContent",
      method: "GET",
      data: {
        ticket: this.data.scene
      },
      callBack: (res) => {
        console.log(res)

        var content = JSON.parse(res.content);
        var ids = JSON.parse(content.content)
        console.log('ids：',ids)
        if (res.type == 1) { //pc团购二维码跳转
          this.setData({
            prodId: ids.prodId,
            groupActivityId: ids.groupActivityId
          })
          this.executionFunction() //所有需要加载的函数
        } else if (res.type == 2) { //分销员二维码跳转
          this.setData({
            prodId: ids.shareProdId,
            distributionCardNo: ids.cardNo
          })
          this.executionFunction() //所有需要加载的函数
        }
      }
    })
  },

  /**
   * 分销绑定用户
   */
  bindDistUser(cardno) {
    http.request({
      url: "/p/distribution/bindUser",
      method: "post",
      data: cardno
    })
  },

  /**
   * 查询分销相关信息
   */
  getDistInfo() {
    //查询分销开关是否开启
    http.request({
      url: "/p/distribution/distributionBasicSet/canDistribution",
      method: "GET",
      dontTrunLogin: true,
      data: {
        shopId: 1,
      },
      callBack: (res) => {
        if (res == 1) {
          this.getIsDistInfo();
        }
      }
    })
  },

  /**
   * 查询用户 是否为分销员
   */
  getIsDistInfo() {
    var isDister = wx.getStorageSync("isDister");
    if (isDister) {
      this.setData({
        isDist: true
      });
      this.getIsDistProd();
    } else {
      http.request({
        url: "/p/distribution/user/distributionUserInfo",
        method: "GET",
        data: {
          shopId: 1,
        },
        callBack: (res) => {
          if (res && res.state == 1) {
            this.setData({
              isDist: true
            });
            this.getIsDistProd();
            wx.setStorageSync("isDister", true);
            wx.setStorageSync("distCardNo", res.cardNo);
          }
        }
      })
    }

  },

  /**
   * 查询是否为分销商品
   */
  getIsDistProd() {
    http.request({
      url: "/p/distribution/prod/isDistributionProd",
      method: "GET",
      data: {
        prodId: this.data.prodId,
      },
      callBack: (res) => {
        if (res) {
          this.setData({
            isDistProd: true
          });
        }
      }
    })
  },

  /**
   * 获取是否关注信息
   */
  getCollection() {
    wx.showLoading();
    var params = {
      url: "/p/user/collection/isCollection",
      method: "GET",
      dontTrunLogin: true,
      data: {
        prodId: this.data.prodId
      },
      callBack: (res) => {
        this.setData({
          isCollection: res
        })
        wx.hideLoading();
      }
    };
    http.request(params);
  },

  /**
   * 添加或者取消收藏商品
   */
  addOrCannelCollection() {
    wx.showLoading();

    var params = {
      url: "/p/user/collection/addOrCancel",
      method: "POST",
      data: this.data.prodId,
      callBack: (res) => {
        this.setData({
          isCollection: !this.data.isCollection
        })
        wx.hideLoading();
      }
    };
    http.request(params);
  },

  // 获取商品信息
  getProdInfo() {
    wx.showLoading();
    var params = {
      url: "/prod/prodInfo",
      method: "GET",
      data: {
        prodId: this.data.prodId,
        // userType: 0
      },
      callBack: (res) => {
        var imgStrs = res.imgs;
        var imgs = imgStrs.split(",");
        var content = util.formatHtml(res.content);
        this.setData({
          imgs: imgs,
          content: content,
          price: res.price,
          prodName: res.prodName,
          groupActivityId: res.groupActivityId,
          prodId: res.prodId,
          brief: res.brief,
          // skuId: res.skuId
          skuList: res.skuList,
          pic: res.pic,
          video: res.video,
        });
        if (res.video) {
          this.getVideoInfo()
        }
        // 团购活动
        if (res.groupActivityId) {
          this.getGroupActivity();
          this.getJoinGroupList();
        }
        //促销活动
        this.getPordDiscountList()
        // 获取优惠券
        this.getCouponList();
        // 组装sku
        this.groupSkuProp(res.skuList);

        wx.hideLoading();
      },
      errCallBack: (err) => {
        console.log(err)
        if (err.statusCode == 400) {
          wx.showModal({
            title: '提示',
            content: err.data,
            showCancel: false,
            success: (res) => {
              if (res.confirm) {
                wx.navigateBack({
                  delta: 1
                })
              }
            }
          })
        }
      }
    };
    http.request(params);
  },
  getProdCommData() {
    http.request({
      url: "/prod/prodCommData",
      method: "GET",
      data: {
        prodId: this.data.prodId,
      },
      callBack: (res) => {
        this.setData({
          prodCommData: res
        })
      }
    })
  },
  // 获取部分评论
  getLittleProdComm() {
    if (this.data.prodCommPage.records.length) {
      return;
    }
    this.getProdCommPage();
  },
  getMoreCommPage(e) {
    this.getProdCommPage();
  },
  // 获取分页获取评论
  getProdCommPage(e) {
    if (e) {
      if (e.currentTarget.dataset.evaluate === this.data.evaluate) {
        return;
      }
      this.setData({
        prodCommPage: {
          current: 0,
          pages: 0,
          records: []
        },
        evaluate: e.currentTarget.dataset.evaluate
      })
    }
    http.request({
      url: "/prod/prodCommPageByProd",
      method: "GET",
      data: {
        prodId: this.data.prodId,
        size: 10,
        current: this.data.prodCommPage.current + 1,
        evaluate: this.data.evaluate
      },
      callBack: (res) => {
        res.records.forEach(item => {
          if (item.pics) {
            item.pics = item.pics.split(',')
          }
        })
        let records = this.data.prodCommPage.records
        records = records.concat(res.records)
        this.setData({
          prodCommPage: {
            current: res.current,
            pages: res.pages,
            records: records
          }
        })
        // 如果商品详情中没有评论的数据，截取两条到商品详情页商品详情
        if (!this.data.littleCommPage.length) {
          this.setData({
            littleCommPage: records.slice(0, 2)
          })
        }
      }
    })
  },

  /**
   * 评论小图点击事件(点击图片显示大图)
   */
  clickImg: function (e) {
    const current = e.target.dataset.src //获取当前点击的 图片 url
    const pics = e.target.dataset.pics
    console.log(current)
    console.log(pics)

    wx.getImageInfo({
      src: current, // 预览图片的地址
      success(e) {
        wx.previewImage({
          current: e.path,
          urls: [e.path]
        })
      }
    })

  },




  /**
   * 优惠券列表
   */
  getCouponList() {
    http.request({
      url: "/coupon/listByProdId",
      method: "GET",
      data: {
        prodId: this.data.prodId,
        shopId: this.data.shopId,
      },
      callBack: (res) => {
        this.setData({
          couponList: res
        })
      }
    })
  },
  getGroupActivity() {
    http.request({
      url: "/groupProd/info",
      method: "GET",
      data: {
        prodId: this.data.prodId,
        groupActivityId: this.data.groupActivityId,
      },
      callBack: (res) => {
        if (res.success) {
          this.setData({
            groupActivity: res.obj,
            isGroupProd: true
          })
          this.setDefaultGroupSku();
          this.groupActivityCountdown(res.obj)
        }
      }
    })
  },
  // 团购倒计时
  groupActivityCountdown(groupActivity) {

    let endOfGroupTime;
    // activityStatus 1 未开始
    if (groupActivity.activityStatus === 1) {
      endOfGroupTime = util.endOfStartTime(util.dateToTimestamp(groupActivity.startTime), new Date().getTime())
    } else {
      endOfGroupTime = util.endOfStartTime(new Date().getTime(), util.dateToTimestamp(groupActivity.endTime))
    }
    this.setData({
      endOfGroupTime: endOfGroupTime,
      groupActivityTimeOut: setTimeout(() => this.groupActivityCountdown(groupActivity), 1000)
    })
  },
  // 可加入的拼团列表
  getJoinGroupList() {
    http.request({
      url: "/groupProd/joinGroupList",
      method: "GET",
      data: {
        prodId: this.data.prodId,
        groupActivityId: this.data.groupActivityId,
        showSize: 3
      },
      callBack: (res) => {
        this.setData({
          joinGroupList: res
        })
        if (res && res.length) {
          this.joinGroupListCountdown(res)
        }
      }
    })
  },
  joinGroupListCountdown(joinGroupList) {
    joinGroupList.forEach(item => {
      item.endOfGroupTime = util.endOfStartTime(new Date().getTime(), util.dateToTimestamp(item.endTime))
    })

    this.setData({
      joinGroupList: joinGroupList,
      joinGroupListTimeOut: setTimeout(() => this.joinGroupListCountdown(joinGroupList), 1000)
    })
  },
  //根据sku的属性 分组
  groupSkuProp: function (skuList) {
    // var skuList = this.data.skuList;
    if (skuList.length == 1 && skuList[0].properties == "") {
      this.setData({
        defaultSku: skuList[0]
      });
      this.setDefaultGroupSku();
      return;
    }
    var skuGroup = {};
    var allProperties = [];
    var propKeys = [];
    this.setData({
      selectedPropObj: {}
    });
    for (var i = 0; i < skuList.length; i++) {
      var defaultSku = this.data.defaultSku;
      var isDefault = false;
      if (!defaultSku && skuList[i].price == this.data.price) { //找到和商品价格一样的那个SKU，作为默认选中的SKU
        defaultSku = skuList[i];
        isDefault = true;
        this.setData({
          defaultSku: defaultSku
        });
      }
      var properties = skuList[i].properties; //版本:公开版;颜色:金色;内存:64GB
      allProperties.push(properties);
      var propList = properties.split(";"); // ["版本:公开版","颜色:金色","内存:64GB"]

      var selectedPropObj = this.data.selectedPropObj;
      for (var j = 0; j < propList.length; j++) {

        var propval = propList[j].split(":"); //["版本","公开版"]
        var props = skuGroup[propval[0]]; //先取出 版本对应的值数组

        //如果当前是默认选中的sku，把对应的属性值 组装到selectedProp
        if (isDefault) {
          propKeys.push(propval[0]);
          selectedPropObj[propval[0]] = propval[1];
        }

        if (props == undefined) {
          props = []; //假设还没有版本，新建个新的空数组
          props.push(propval[1]); //把 "公开版" 放进空数组
        } else {
          if (!this.array_contain(props, propval[1])) { //如果数组里面没有"公开版"
            props.push(propval[1]); //把 "公开版" 放进数组
          }
        }
        skuGroup[propval[0]] = props; //最后把数据 放回版本对应的值
      }
      this.setData({
        selectedPropObj: selectedPropObj,
        propKeys: propKeys
      });
    }
    this.parseSelectedObjToVals();
    this.setData({
      skuGroup: skuGroup,
      allProperties: allProperties
    });
    this.setDefaultGroupSku();
  },

  //将已选的 {key:val,key2:val2}转换成 [val,val2]
  parseSelectedObjToVals: function () {
    var selectedPropObj = this.data.selectedPropObj;
    var selectedProperties = "";
    var selectedProp = [];
    for (var key in selectedPropObj) {
      selectedProp.push(selectedPropObj[key]);
      selectedProperties += key + ":" + selectedPropObj[key] + ";";
    }
    selectedProperties = selectedProperties.substring(0, selectedProperties.length - 1);
    this.setData({
      selectedProp: selectedProp,
      selectedProperties: selectedProperties
    });

    var findSku = false;
    for (var i = 0; i < this.data.skuList.length; i++) {
      if (this.data.skuList[i].properties == selectedProperties) {
        findSku = true;
        this.setData({
          defaultSku: this.data.skuList[i]
        });
        break;
      }
    }
    this.setData({
      findSku: findSku
    });
    this.setDefaultGroupSku();
  },

  //点击选择规格
  toChooseItem: function (e) {
    var ok = e.currentTarget.dataset.ok;
    if (ok == 0) {
      return;
    }
    var val = e.currentTarget.dataset.val;
    var key = e.currentTarget.dataset.key;
    var selectedPropObj = this.data.selectedPropObj;
    selectedPropObj[key] = val;
    this.setData({
      selectedPropObj: selectedPropObj
    });
    this.parseSelectedObjToVals();
  },

  //判断数组是否包含某对象
  array_contain: function (array, obj) {
    for (var i = 0; i < array.length; i++) {
      if (array[i] == obj) //如果要求数据类型也一致，这里可使用恒等号===
        return true;
    }
    return false;
  },

  /**
   * 设置选中的拼团sku
   */
  setDefaultGroupSku() {
    if (this.data.groupActivityId) {
      var groupSkuList = this.data.groupActivity.groupSkuList;
      if (groupSkuList) {
        for (var i = 0; i < groupSkuList.length; i++) {
          if (groupSkuList[i].properties == this.data.selectedProperties) {
            this.setData({
              detaultGroupSku: groupSkuList[i]
            });
            break;
          }
        }
      }
    }
  },


  /**
   * 去凑团
   */
  toSpellGroupDetail(e) {
    const groupTeamId = e.currentTarget.dataset.groupteamid
    util.checkAuthInfo(()=>{
      wx.navigateTo({
        url: '/pages/spellGroupDetails/spellGroupDetails?groupTeamId=' + groupTeamId,
      })
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.videoContext = wx.createVideoContext('myVideo')
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      totalCartNum: app.globalData.totalCartCount,
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.setData({
      skuShow: false
    })
    if (this.data.isPlaying) {
      this.stopPlay()
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearTimeout(this.data.joinGroupListTimeOut)
    clearTimeout(this.data.groupActivityTimeOut)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 跳转到首页
   */
  toHomePage: function () {
    wx.switchTab({
      url: '/pages/index/index',
    })
  },

  /**
   * 跳转到购物车
   */
  toCartPage: function () {
    wx.switchTab({
      url: '/pages/basket/basket',
    })
  },

  /**
   * 加入购物车
   */
  addToCart: function (event) {
    if (this.data.isPlaying) {
      this.stopPlay()
    }
    if (!this.data.findSku) {
      return;
    }
    if (!this.data.skuShow) {
      this.setData({
        skuShow: true
      })
      return;
    }
    var ths = this;

    // 查看是否授权
    util.checkAuthInfo(()=>{
      ths.callChangeItem();
    })
  },

  callChangeItem() {
    wx.showLoading({
      mask: true
    });
    http.request({
      url: "/p/shopCart/changeItem",
      method: "POST",
      data: {
        basketId: 0,
        count: this.data.prodNum,
        prodId: this.data.prodId,
        shopId: this.data.shopId,
        skuId: this.data.defaultSku.skuId,
        distributionCardNo: this.data.distributionCardNo
      },
      callBack: (res) => {
        this.setData({
          totalCartNum: this.data.totalCartNum + this.data.prodNum,
          skuShow: false
        });
        wx.hideLoading();
        wx.showToast({
          title: "加入购物车成功",
          icon: "none"
        })
      }
    });
  },


  /**
   * 立即购买
   */
  buyNow: function () {
    if (this.data.isPlaying) {
      this.stopPlay()
    }
    if (!this.data.findSku) {
      return;
    }
    if (!this.data.skuShow) {
      this.setData({
        skuShow: true
      })
      return;
    }
    var ths = this;
    wx.showLoading({
      mask: true
    });
    // 查看是否授权
    util.checkAuthInfo(()=>{
      wx.hideLoading();
      wx.setStorageSync("orderItem", JSON.stringify({
        prodId: ths.data.prodId,
        skuId: ths.data.defaultSku.skuId,
        prodCount: ths.data.prodNum,
        shopId: ths.data.shopId,
        distributionCardNo: ths.data.distributionCardNo
      }));
      wx.navigateTo({
        url: '/pages/submit-order/submit-order?orderEntry=1',
      })
    })
  },

  /**
   * 减数量
   */
  onCountMinus: function () {
    var prodNum = this.data.prodNum;
    if (prodNum > 1) {
      this.setData({
        prodNum: prodNum - 1
      });
    }
  },

  /**
   * 加数量
   */
  onCountPlus: function () {
    var prodNum = this.data.prodNum;
    if (prodNum < 1000) {
      this.setData({
        prodNum: prodNum + 1
      });
    }
  },

  /**
   * 用户点击转发
   */
  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      var cardno = wx.getStorageSync("distCardNo");
      return {
        title: this.data.prodName,
        path: '/pages/prod/prod?prodid=' + this.data.prodId + '&cardno=' + cardno,
        imageUrl: this.data.pic
      }
    } else {
      return {
        title: this.data.prodName,
        path: '/pages/prod/prod?prodid=' + this.data.prodId
      }
    }
  },


  /**
   * 通过商品id获取商品所有促销活动
   */
  getPordDiscountList() {
    http.request({
      url: "/marking/discount/getDiscountByProdId",
      method: "GET",
      data: {
        prodId: this.data.prodId
      },
      callBack: res => {
        this.setData({
          prodDiscountList: res
        })
      }
    })
  },
  /**
   * 促销活动弹窗
   */
  clickDiscount: function () {
    var showDiscountPopup = !this.data.showDiscountPopup
    this.setData({
      showDiscountPopup
    })
    if (this.data.isPlaying) {
      this.stopPlay()
    }
  },


  /**
   * 优惠券
   */
  showPopup: function () {
    if (this.data.loadCouponIds) {
      this.setData({
        popupShow: true
      });
      if (this.data.isPlaying) {
        this.stopPlay()
      }
      return;
    }
    util.checkAuthInfo(()=>{
      http.request({
        url: "/p/myCoupon/listCouponIds",
        method: "GET",
        data: {},
        callBack: (couponIds) => {
          var couponList = this.data.couponList;
          couponList.forEach(coupon => {
            if (couponIds && couponIds.length) {
              // 领取该优惠券数量
              var couponLimit = 0;
              couponIds.forEach(couponId => {
                if (couponId == coupon.couponId) {
                  couponLimit++;
                }
              });
              // 小于用户领取优惠券上限，可以领取优惠券
              if (couponLimit < coupon.limitNum) {
                coupon.canReceive = true;
              } else {
                coupon.canReceive = false;
              }
            } else {
              coupon.canReceive = true;
            }
          });
          this.setData({
            couponList: couponList,
            popupShow: true,
            loadCouponIds: true
          })
        }
      })
    })
  },
  showSku: function () {
    if (this.data.isPlaying) {
      this.stopPlay()
    }
    this.setData({
      skuShow: true,
      skuShowType: 0,
    });
  },
  showGroupSku: function () {
    if (this.data.isPlaying) {
      this.stopPlay()
    }
    this.setData({
      skuShow: true,
      skuShowType: 1
    });

  },
  showComment: function () {
    if (this.data.isPlaying) {
      this.stopPlay()
    }
    this.setData({
      commentShow: true
    });
  },

  closePopup: function () {
    this.setData({
      popupShow: false,
      skuShow: false,
      commentShow: false
    });
  },


  onShowShare: function () {
    if (this.data.isPlaying) {
      this.stopPlay()
    }
    this.setData({
      shareShow: true
    });
  },
   /**
   * 回到顶部
   */
  backToTop: function () {
    wx.pageScrollTo({
      duration: 300,
      scrollTop: 0
    })
  },
  /**
   * 监听页面滚动
   */
  onPageScroll: function (e) {
    if (e.scrollTop > 80) {
      this.setData({
        showBacktop: true
      })
    } else if (e.scrollTop < 80) {
      this.setData({
        showBacktop: false
      })
    }
  },

  closeEarn: function () {
    this.setData({
      shareShow: false

    })
  },

  toDistCenterPage: function () {
    wx.navigateTo({
      url: '/pages/dis-center/dis-center',
    })
  },

  /**
   * 生成小程序二维码
   */
  genWeixinCode() {
    wx.showLoading({
      mask: true
    })
    var cardNo = wx.getStorageSync("distCardNo");
    var content = JSON.stringify({
      shareProdId: this.data.prodId,
      cardNo: cardNo,
    })
    
    http.request({
      url: "/qrcodeTicket/miniQrCode",
      method: "GET",
      responseType: 'arraybuffer',
      data: {
        content: content,
        type: 2
      },
      callBack: (res) => {
        this.setData({
          wxCodeShow: true,
          shareShow: false,
          shareWxCode: "data:image/jpg;base64," + wx.arrayBufferToBase64(res)
        });
        wx.hideLoading();
      }
    })
  },

  /**
   * 关闭二维码弹窗
   */
  closeCodePopup() {
    this.setData({
      wxCodeShow: false
    });
  },

  /**
   * 保存图片至相册
   */
  downloadImg() {
    var ths = this
    var imgSrc = this.data.shareWxCode.slice(22); //base64编码
    var save = wx.getFileSystemManager();
    save.writeFile({
      filePath: wx.env.USER_DATA_PATH + '/分享商品-' + this.data.shareProdName + '.png',
      data: imgSrc,
      encoding: 'base64',
      success: res => {
        wx.saveImageToPhotosAlbum({
          filePath: wx.env.USER_DATA_PATH + '/分享商品-' + this.data.shareProdName + '.png',
          success: function (res) {
            wx.showToast({
              title: '保存成功',
            })
            ths.setData({
              wxCodeShow: false
            })
          },
          fail: function (err) {
            wx.showModal({
              title: '提示',
              content: '保存图片需要授予存储权限',
              success: modalRes => {
                if (modalRes.confirm) {
                  wx.openSetting({
                    success(settingdata) {
                      if (settingdata.authSetting['scope.writePhotosAlbum']) {
                        console.log('用户权限成功')
                      } else {
                        console.log('用户取消权限')
                      }
                    }
                  })
                }
              }
            })
          }
        })
        console.log(res)
      },
      fail: err => {
        console.log(err)
      }
    })
  },

  /**
   * 获取用户信息
   */
  onGotUserInfo: function (e) {
    if (e.detail.errMsg != "getUserInfo:fail auth deny") {
      this.setData({
        isAuthInfo: true
      });
      http.updateUserInfo();
    }
  },
  groupConfirmOrder: function (e) {
    if (!this.data.findSku) {
      return;
    }
    var ths = this;
    wx.showLoading({
      mask: true
    });
    // 查看是否授权
    util.checkAuthInfo(() => {
      wx.setStorageSync("groupOrderItem", JSON.stringify({
        groupSkuId: ths.data.detaultGroupSku.groupSkuId, // this.data.groupSkuId,
        prodCount: ths.data.prodNum, // this.data.prodNum,
        groupTeamId: e.currentTarget.dataset.teamid // this.data.groupTeamId
      }));
      wx.navigateTo({
        url: '/pages/groupConfirmOrder/groupConfirmOrder',
      })
    })
  },

  /**
   * 视频信息
   */
  getVideoInfo() {
    wx.showLoading()
    wx.request({
      url: this.data.video + '?avinfo',
      success: res => {
        wx.hideLoading()
        let time = Number(res.data.format.duration).toFixed(0)
        this.setData({
          videoDuration: time < 60 ? '00′' + time + '″' : parseInt(time / 60) + '′' + time % 60 + '″'
        })
      }
    })
  },

  /**
   * 视频播放/停止按钮
   */
  videoOper() {
    if (this.data.isPlaying) {
      this.stopPlay()
    } else {
      this.startPlay()
    }
  },

  /**
   * 视频播放结束时
   */
  playEnd() {
    this.stopPlay()
  },

  startPlay() {
    this.setData({
      isPlaying: true,
    })
    setTimeout(() => {
      this.videoContext.seek(0)
      this.videoContext.play()
    }, 200)
  },
  stopPlay() {
    this.setData({
      isPlaying: false
    })
    setTimeout(() => {
      this.videoContext.seek(0)
      this.videoContext.stop()
    }, 200)
  },
})
